package org.example.channel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 读写文件
 */
public class Demo3 {
    public static void main(String[] args) throws FileNotFoundException {
        //创建文件输入\输出流
        try (FileInputStream fileInputStream = new FileInputStream("demo.txt");
             FileOutputStream fileOutputStream = new FileOutputStream("demo1.txt")) {
            //获取输入\输出通道
            FileChannel inputChannel = fileInputStream.getChannel();
            FileChannel outputChannel = fileOutputStream.getChannel();
            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //循环读取
            while (true) {
                byteBuffer.clear();
                //读取数据
                int read = inputChannel.read(byteBuffer);
                System.out.println(read);
                //如等于-1终止
                if (read == -1) break;
                //翻转
                byteBuffer.flip();
                //写入数据
                int write = outputChannel.write(byteBuffer);
                System.out.println(write);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
